package com.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import com.bean.ProductType;
import com.dao.ProductTypeServices;
import com.mapper.ProductTypeMapper;

public class ProductTypeServicesImpl implements ProductTypeServices{
	SqlSessionFactory sqlSessionFactory=SqlSessionFactoryMain.createSqlSessionFractory();
	SqlSession sqlSession=null;
	@Override
	public Map<String,Object> save(ProductType t) {
		Map<String,Object>map=new HashMap<String, Object>();
		Boolean flag=false;
		String massage=null;
		sqlSession=sqlSessionFactory.openSession();
		ProductTypeMapper productTypeMapper= sqlSession.getMapper(com.mapper.ProductTypeMapper.class);
		List<ProductType>productTypes= productTypeMapper.findProductType(" product_type_name='"+t.getProcuctTypeName()+"'"," sort desc");
		if (productTypes.isEmpty()) {
			massage="添加productType成功";
			flag=true;
			productTypeMapper.insertProductType(t);
			sqlSession.commit();
		}else {
			massage="productType已存在";
		}
		sqlSession.close();
		map.put("flag",flag);
		map.put("massage",massage);
		return map;
	}

	@Override
	public boolean delete(String id) {
		sqlSession=sqlSessionFactory.openSession();
		ProductTypeMapper productTypeMapper= sqlSession.getMapper(com.mapper.ProductTypeMapper.class);
		productTypeMapper.deleteProductTypeById(Integer.parseInt(id));
		sqlSession.commit();
		sqlSession.close();
		return true;
	}

	@Override
	public boolean update(ProductType t) {
		sqlSession=sqlSessionFactory.openSession();
		ProductTypeMapper productTypeMapper= sqlSession.getMapper(com.mapper.ProductTypeMapper.class);
		productTypeMapper.updateProductTypeById(t);
		sqlSession.commit();
		sqlSession.close();
		return true;
	}

	@Override
	public ProductType findByid(Integer id) {
		sqlSession=sqlSessionFactory.openSession();
		ProductTypeMapper productTypeMapper= sqlSession.getMapper(com.mapper.ProductTypeMapper.class);
		ProductType productType= productTypeMapper.findProductTypeById(id);
		return  productType;
	}

	@Override
	public List<ProductType> findByWhere(String strWhere, String strOrder) {
		sqlSession=sqlSessionFactory.openSession();
		ProductTypeMapper productTypeMapper= sqlSession.getMapper(com.mapper.ProductTypeMapper.class);
		if (strWhere==null) {
			strWhere=" 1=1 ";
		}
		if (strOrder==null) {
			strOrder=" sort desc";
		}
		List<ProductType>productTypes=productTypeMapper.findProductType(strWhere, strOrder);
		return productTypes;
	}
	public static void main(String[] args) {
		ProductTypeServices productTypeServices= new ProductTypeServicesImpl();
		System.out.println(productTypeServices.findByid(1));
	}
}
